package com.paw.ruoyi.admin.biz.service;

import java.util.concurrent.TimeUnit;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.paw.ruoyi.admin.common.constant.RedisPrefixKeyConstant;
import com.paw.ruoyi.admin.common.context.UserContext;
import com.paw.ruoyi.admin.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
public class TokenService {


  /**
   * 令牌有效期（默认30分钟）
   */
  @Value("${token.expireTime:30}")
  private int expireTime;

  protected static final long MILLIS_SECOND = 1000;

  protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

  private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;


  @Autowired
  private StringRedisTemplate stringRedisTemplate;



  /**
   * 删除用户身份信息
   */
  public void delLoginUser (String token) {
    if (StringUtils.isNotEmpty(token)) {
      String userKey = getTokenKey(token);
      stringRedisTemplate.delete(userKey);
    }
  }

  /**
   * 创建令牌
   *
   * @return 令牌
   */
  public String createToken (UserContext userContext) {
    String token = IdUtil.fastSimpleUUID();
    stringRedisTemplate.opsForValue().set(getTokenKey(token), JSON.toJSONString(userContext), expireTime, TimeUnit.MINUTES);
    return token;
  }

  public void updateCacheUserContext (String token,UserContext userContext) {
    stringRedisTemplate.opsForValue().set(getTokenKey(token), JSON.toJSONString(userContext), expireTime, TimeUnit.MINUTES);
  }

  /**
   * 验证令牌有效期，相差不足20分钟，自动刷新缓存
   *
   * @return 令牌
   */
  public Boolean verifyToken (String token) {
    String tokenKey = getTokenKey(token);
    return stringRedisTemplate.hasKey(tokenKey);
  }

  /**
   * 刷新令牌有效期
   *
   */
  public void refreshToken (String token) {
    if(StrUtil.isEmpty(token)){
      return;
    }
    String tokenKey = getTokenKey(token);
    Long expire = stringRedisTemplate.getExpire(tokenKey,TimeUnit.MINUTES);
    if (expire <= MILLIS_MINUTE_TEN) {
      stringRedisTemplate.expire(tokenKey, expireTime, TimeUnit.MINUTES);
    }

  }




  private String getTokenKey (String key) {
    return RedisPrefixKeyConstant.getKey(RedisPrefixKeyConstant.PRE_TOKEN,key);
  }
}
